package com.zzf.design.factory.db.v2;

import com.zzf.design.factory.db.*;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * @author zzf
 * @date 2018/8/26 09:57.
 */
public class DataAccess {

    private static String pack = "com.zzf.design.factory.db.";
    private static String db = "SqlServer";//Access

    //配置文件处理
    private static Properties properties = new Properties();
    static {

        //配置文件获取db
        try {
            ResourceUtils.getFile("classpath:db.properties");
            properties.load(DataAccess.class.getClassLoader().getResourceAsStream("db.properties"));

            db = properties.getProperty("db");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据 db 参数选择
    public static IUserDao creatUser() {
        IUserDao userDao = null;

        switch (db) {
            case "SqlServer":
                userDao = new SqlServerUserDao();
                break;
            case "Access":
                userDao = new AccessUserDao();
                break;

        }
        return userDao;
    }

    public static IDepartmentDao creatDepartment() {
        IDepartmentDao departmentDao = null;

        switch (db) {
            case "SqlServer":
                departmentDao = new SqlServerDepartmentDao();
                break;
            case "Access":
                departmentDao = new AccessDepartmentDao();
                break;

        }
        return departmentDao;
    }


    /**
     * 反射实现
     * @return
     */
    public static IUserDao createUserDaoV2() {
        try {
            return (IUserDao) Class.forName(pack + db + "UserDao").newInstance();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static IDepartmentDao createDepartmentDaoV2() {
        try {
            return (IDepartmentDao) Class.forName(pack + db + "DepartmentDao").newInstance();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
